package com.qzw.common.util;

import com.qzw.common.api.base.PageReq;
import com.qzw.common.api.base.PageResp;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;

/**
 * @author ：quziwei
 * @date ：Created in 2020/6/1 5:37 下午
 * @description：分页工具类
 */
public class PageUtils {

    public <M> PageResp<M> page2PageResp(Page page) {
        PageResp<M> pageResp = null;
        if (!ObjectUtils.isEmpty(page)) {
            pageResp = new PageResp<>();
            pageResp.setPageNumber(page.getNumber() + 1);
            pageResp.setPageSize(page.getSize());
            pageResp.setTotalPage(page.getTotalPages());
            pageResp.setTotalRow(page.getTotalElements());
            pageResp.setList(new ArrayList<>());
        }
        return pageResp;
    }

    public PageRequest pageReq2PageRequest(PageReq pageReq) {
        PageRequest pageRequest = null;
        if (!ObjectUtils.isEmpty(pageReq)) {
            pageRequest = PageRequest.of(pageReq.getPageNumber() - 1, pageReq.getPageSize());
        }
        return pageRequest;
    }

    public PageRequest pageReq2PageRequest(PageReq pageReq, Sort sort) {
        PageRequest pageRequest = null;
        if (!ObjectUtils.isEmpty(pageReq)) {
            pageRequest = PageRequest.of(pageReq.getPageNumber() - 1, pageReq.getPageSize(), sort);
        }
        return pageRequest;
    }
}
